
const productManagementController = function(HttpService) {
  'ngInject';

  const vm = this;

  vm.products = [];
  vm.productCategories = [];
  vm.isLoading = false;
  vm.showCreateForm = false;
  vm.showModulesView = false;
  vm.selectedProduct = null;
  vm.productModules = [];

  vm.filters = {
    category_id: '',
    vendor: '',
    support_level: '',
    business_value: '',
    search: ''
  };

  vm.newProduct = {
    name: '',
    code: '',
    category_id: '',
    vendor: '',
    version: '',
    description: '',
    launch_date: '',
    support_level: 'full',
    business_value: 'medium',
    user_count: 0,
    documentation_url: '',
    repository_url: ''
  };

  // 支持级别选项
  vm.supportLevels = [
    { value: 'full', label: '完全支持' },
    { value: 'maintenance', label: '仅维护' },
    { value: 'limited', label: '有限支持' },
    { value: 'none', label: '无支持' }
  ];

  // 业务价值选项
  vm.businessValues = [
    { value: 'critical', label: '关键' },
    { value: 'high', label: '高' },
    { value: 'medium', label: '中' },
    { value: 'low', label: '低' }
  ];

  // 初始化
  vm.$onInit = function() {
    loadProducts();
    loadProductCategories();
  };

  function loadProducts() {
    vm.isLoading = true;
    
    const params = { include_modules: 'false' };
    if (vm.filters.category_id) params.category_id = vm.filters.category_id;
    if (vm.filters.vendor) params.vendor = vm.filters.vendor;
    if (vm.filters.support_level) params.support_level = vm.filters.support_level;
    if (vm.filters.business_value) params.business_value = vm.filters.business_value;
    if (vm.filters.search) params.search = vm.filters.search;

    HttpService.products.list(params)
      .then(response => {
        if (response.success) {
          vm.products = response.data;
        } else {
          console.error('加载产品列表失败:', response.message);
          alert('加载产品列表失败：' + response.message);
        }
      })
      .catch(error => {
        console.error('加载产品列表失败:', error);
        alert('加载产品列表失败：' + (error.message || '网络错误'));
      })
      .finally(() => {
        vm.isLoading = false;
      });
  }

  function loadProductCategories() {
    HttpService.productCategories.list({ status: 1 })
      .then(response => {
        if (response.success) {
          vm.productCategories = response.data;
        }
      })
      .catch(error => {
        console.error('加载产品分类失败:', error);
      });
  }

  function loadProductModules(productId) {
    HttpService.productModules.list({ product_id: productId })
      .then(response => {
        if (response.success) {
          vm.productModules = response.data;
        } else {
          vm.productModules = [];
        }
      })
      .catch(error => {
        console.error('加载产品模块失败:', error);
        vm.productModules = [];
      });
  }

  vm.searchProducts = function() {
    loadProducts();
  };

  vm.clearFilters = function() {
    vm.filters = {
      category_id: '',
      vendor: '',
      support_level: '',
      business_value: '',
      search: ''
    };
    loadProducts();
  };

  vm.showCreateProductForm = function() {
    vm.showCreateForm = true;
    vm.newProduct = {
      name: '',
      code: '',
      category_id: '',
      vendor: '',
      version: '',
      description: '',
      launch_date: '',
      support_level: 'full',
      business_value: 'medium',
      user_count: 0,
      documentation_url: '',
      repository_url: ''
    };
  };

  vm.hideCreateForm = function() {
    vm.showCreateForm = false;
    if (vm.productForm) {
      vm.productForm.$setPristine();
      vm.productForm.$setUntouched();
    }
  };

  vm.createProduct = function() {
    if (vm.productForm.$invalid) {
      alert('请填写必填字段');
      return;
    }

    vm.isLoading = true;

    HttpService.products.create(vm.newProduct)
      .then(response => {
        if (response.success) {
          alert('产品创建成功！');
          vm.hideCreateForm();
          loadProducts();
        } else {
          alert('产品创建失败：' + response.message);
        }
      })
      .catch(error => {
        alert('产品创建失败：' + (error.message || '网络错误'));
      })
      .finally(() => {
        vm.isLoading = false;
      });
  };

  vm.viewProductModules = function(product) {
    vm.selectedProduct = product;
    vm.showModulesView = true;
    loadProductModules(product.id);
  };

  vm.hideModulesView = function() {
    vm.showModulesView = false;
    vm.selectedProduct = null;
    vm.productModules = [];
  };

  // 获取支持级别标签
  vm.getSupportLevelLabel = function(level) {
    const supportLevel = vm.supportLevels.find(s => s.value === level);
    return supportLevel ? supportLevel.label : level;
  };

  // 获取业务价值标签
  vm.getBusinessValueLabel = function(value) {
    const businessValue = vm.businessValues.find(b => b.value === value);
    return businessValue ? businessValue.label : value;
  };

  // 获取业务价值徽章样式
  vm.getBusinessValueBadgeClass = function(value) {
    const classMap = {
      'critical': 'badge-danger',
      'high': 'badge-warning',
      'medium': 'badge-info',
      'low': 'badge-secondary'
    };
    return classMap[value] || 'badge-secondary';
  };

  // 获取支持级别徽章样式
  vm.getSupportLevelBadgeClass = function(level) {
    const classMap = {
      'full': 'badge-success',
      'maintenance': 'badge-info',
      'limited': 'badge-warning',
      'none': 'badge-secondary'
    };
    return classMap[level] || 'badge-secondary';
  };

  // 获取模块类型标签
  vm.getModuleTypeLabel = function(type) {
    const typeMap = {
      'core': '核心模块',
      'plugin': '插件模块',
      'addon': '附加模块',
      'integration': '集成模块'
    };
    return typeMap[type] || type;
  };

  // 获取复杂度标签
  vm.getComplexityLabel = function(level) {
    const levelMap = {
      'simple': '简单',
      'medium': '中等',
      'complex': '复杂',
      'critical': '关键'
    };
    return levelMap[level] || level;
  };
};

const productManagementComponent = {
  templateUrl: 'src/app/pages/product-management/product-management.template.html',
  controller: productManagementController
};

function initProductManagementController() {
  const angular = window.angular;
  
  if (!angular) {
    console.error('Angular 未找到，无法初始化产品管理控制器模块');
    return;
  }

  angular.module('app.pages.productManagement', [])
    .component('productManagementPage', productManagementComponent);
}

// Listen for vendor libs loaded event
window.addEventListener('vendorLibsLoaded', () => {
  initProductManagementController();
});

// If Angular already loaded, init directly  
if (window.angular) {
  initProductManagementController();
}